/*
#          .,:,,,                                        .::,,,::.          
#        .::::,,;;,                                  .,;;:,,....:i:         
#        :i,.::::,;i:.      ....,,:::::::::,....   .;i:,.  ......;i.        
#        :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i.        
#        ;;..,::::;;;;ri,,,.                    ..,,:;s1s1ssrr;,.;r,        
#        :;. ,::;ii;:,     . ...................     .;iirri;;;,,;i,        
#        ,i. .;ri:.   ... ............................  .,,:;:,,,;i:        
#        :s,.;r:... ....................................... .::;::s;        
#        ,1r::. .............,,,.,,:,,........................,;iir;        
#        ,s;...........     ..::.,;:,,.          ...............,;1s        
#       :i,..,.              .,:,,::,.          .......... .......;1,       
#      ir,....:rrssr;:,       ,,.,::.     .r5S9989398G95hr;. ....,.:s,      
#     ;r,..,s9855513XHAG3i   .,,,,,,,.  ,S931,.,,.;s;s&BHHA8s.,..,..:r:     
#    :r;..rGGh,  :SAG;;G@BS:.,,,,,,,,,.r83:      hHH1sXMBHHHM3..,,,,.ir.    
#   ,si,.1GS,   sBMAAX&MBMB5,,,,,,:,,.:&8       3@HXHBMBHBBH#X,.,,,,,,rr    
#   ;1:,,SH:   .A@&&B#&8H#BS,,,,,,,,,.,5XS,     3@MHABM&59M#As..,,,,:,is,   
#  .rr,,,;9&1   hBHHBB&8AMGr,,,,,,,,,,,:h&&9s;   r9&BMHBHMB9:  . .,,,,;ri.  
#  :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr.      ...,:rs.  
#  ;s.     .:sS8G8GG889hi.        ....,,:;:,.:irssrriii:,.        ...,,i1,  
#  ;1,         ..,....,,isssi;,        .,,.                      ....,.i1,  
#  ;h:               i9HHBMBBHAX9:         .                     ...,,,rs,  
#  ,1i..            :A#MBBBBMHB #  .r1,..        ,..;3BMBBBHBB#Bh.     ..                    ....,,,,,i1;   
#   :h;..       .,..;,1XBMMMMBXs,.,, .. :: ,.               ....,,,,,,ss.   
#    ih: ..    .;;;, ;;:s58A3i,..    ,. ,.:,,.             ...,,,,,:,s1,    
#    .s1,....   .,;sh,  ,iSAXs;.    ,.  ,,.i85            ...,,,,,,:i1;     
#     .rh: ...     rXG9XBBM#M#MHAX3hss13&&HHXr         .....,,,,,,,ih;      
#      .s5: .....    i598X&&A&AAAAAA&XG851r:       ........,,,,:,,sh;       
#      . ihr, ...  .         ..                    ........,,,,,;11:.       
#         ,s1i. ...  ..,,,..,,,.,,.,,.,..       ........,,.,,.;s5i.         
#          .:s1r,......................       ..............;shs,           
#          . .:shr:.  ....                 ..............,ishs.             
#              .,issr;,... ...........................,is1s;.               
#                 .,is1si;:,....................,:;ir1sr;,                  
#                    ..:isssssrrii;::::::;;iirsssssr;:..                    
#                         .,::iiirsssssssssrri;;:.
*/
package com.itheima.health.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.*;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.*;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * <dl>
 * <dd>描述: ~ UserServiceImpl</dd>
 * <dd>创建时间：  11:47 2021/2/23</dd>
 * <dd>创建人： guodong</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author         Version     Description
 * ------------------------------------------------------------------
 * 2021/2/23      guodong         1.0        1.0 Version
 * </pre>
 * </dl>
 */
@DubboService //此处需要注意是一个dubbo 服务 不要加错注解
@Slf4j
@Transactional//添加事务
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private PermissionMapper permissionMapper;
	@Autowired
	UserRoleMapper userRoleMapper;


	@Override
	public List<Integer> findMenuIdsById(Integer id) {
		log.info("[查询菜单id集合中------------------]id:{}",id);
		List<Integer> menuIds= userMapper.findMenuIdsById(id);
		log.info("[菜单id集合]menuIds:{}",menuIds);
		return menuIds;
	}

	@Override
	public void add(Integer[] RolesIds, User user) {
		log.info("[前端RolesIds,user]RolesIds:{},user:{}", RolesIds, user);
		userMapper.insertSelective(user);
		//2.维护中间关联关系表
		userRoleMapper.insertMany(user.getId(),RolesIds);

	}
/**
 * @Author: wty
 * @Date: 11:15 2021/3/12
 * @Parms [id]
 * @ReturnType: java.util.List<java.lang.Integer>
 * @Description: 查询用户的所有角色
*/
	@Override
	public List<Integer> findRolesIdsById(Integer id) {
		UserRole userRole = new UserRole();
		userRole.setUserId(id);
		List<UserRole> userRoleList = userRoleMapper.select(userRole);
		List<Integer> rolesIds = new ArrayList<>();
		for (UserRole role : userRoleList) {
			rolesIds.add(role.getRoleId());
		}
		return rolesIds;
	}
/**
 * @Author: wty 
 * @Date: 18:07 2021/3/12
 * @Parms [RolesIds, menuIds, user]
 * @ReturnType: void
 * @Description: 添加用户
*/
	@Override
	@Transactional
	public void edit(Integer[] RolesIds, User user) {
		//更新用户

		userMapper.updateByPrimaryKeySelective(user);
		//维护用户和角色的关系表
		UserRole userRole = new UserRole();
		userRole.setUserId(user.getId());
		userRoleMapper.delete(userRole);

		userRoleMapper.insertMany(user.getId(),RolesIds);
	}

	@Override
	public User findById(Integer id) {
		User user = userMapper.selectByPrimaryKey(id);
		user.setPassword("");
		return user;
	}

	/**
	 * @Author: guodong
	 * @Date: 11:49 2021/2/23
	 * @Parms [username]
	 * @ReturnType: com.itheima.health.pojo.User
	 * @Description: 根据用户名查询用户
	 */
	@Override
	public User findUserByName(String username) {
		//return userMapper.findUserByName(username);
		//使用tk完成查询
		User user1 = new User();
		user1.setUsername(username);
		//select * from t_user where username = username and password = 123
		User user = userMapper.selectOne(user1);
		//查询角色信息
		if (user == null){
		    return null;
		}
		Set<Role> roles = roleMapper.findByUserId(user.getId());
		user.setRoles(roles);
		//查询权限信息
		for (Role role : roles) {
			Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
			role.setPermissions(permissions);
		}
		log.info("[=====user====]user:{}",user);
		return user;
	}

	@Override
	public void delete(Integer id) {
		UserRole userRole = new UserRole();
		userRole.setUserId(id);
		log.info("[---userRole---]userRole:{}", userRole);
		userRoleMapper.delete(userRole);
		userMapper.deleteByPrimaryKey(id);

	}

	@Override
	public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(queryString)) {
            criteria.orLike("username", "%" + queryString + "%");
            criteria.orLike("telephone", "%" + queryString + "%");
        }
        Page<User> page = (Page<User>) userMapper.selectByExample(example);
	    return new PageResult(page.getTotal(), page.getResult());

	}
}
